#include "dma.h"

uint32_t DMA_Size = DMA_Buffer_Length;
DMA_InitTypeDef DMA_InitStructure;

// DMA Initialization(DMA初始化)
void USART_DMA_Init(DMA_Channel_TypeDef *DMA_Channel, uint32_t srcAddress, uint32_t dstAddress, uint32_t dataLength)
{
    DMA_Size = dataLength;
    RCC_AHBPeriphClockCmd(RCC_AHBPeriph_DMA1, ENABLE);

    // DMA Initialization(DMA初始化)
    DMA_InitStructure.DMA_PeripheralBaseAddr = srcAddress;                  // src address(外设基地址)
    DMA_InitStructure.DMA_PeripheralDataSize = DMA_PeripheralDataSize_Byte; // data wide(8位外设数据宽度)
    DMA_InitStructure.DMA_PeripheralInc = DMA_PeripheralInc_Enable;         // 外设地址自增
    DMA_InitStructure.DMA_MemoryBaseAddr = dstAddress;                      // dst address(内存目的地址)
    DMA_InitStructure.DMA_MemoryDataSize = DMA_MemoryDataSize_Byte;         // data wide(8位内存数据宽度)
    DMA_InitStructure.DMA_MemoryInc = DMA_MemoryInc_Enable;                 // 内存地址自增
    DMA_InitStructure.DMA_DIR = DMA_DIR_PeripheralSRC;                      // 外设为源地址
    DMA_InitStructure.DMA_BufferSize = DMA_Size;                            // 数据长度
    DMA_InitStructure.DMA_Mode = DMA_Mode_Normal;                           // 普通模式
    DMA_InitStructure.DMA_M2M = DMA_M2M_Enable;                             // 内存到内存模式
    DMA_InitStructure.DMA_Priority = DMA_Priority_Medium;                   // 优先级
    DMA_Init(DMA_Channel, &DMA_InitStructure);                              // 初始化DMA

    DMA_Cmd(DMA_Channel, DISABLE); // 关闭DMA
}

// DMA Transfer Data(DMA传输数据)
void USART_DMA_Transfer_Data(DMA_Channel_TypeDef *DMA_Channel)
{
    DMA_Cmd(DMA_Channel, DISABLE);                 // 关闭DMA
    DMA_SetCurrDataCounter(DMA_Channel, DMA_Size); // 设置DMA数据长度
    DMA_Cmd(DMA_Channel, ENABLE);                  // 打开DMA

    while (DMA_GetFlagStatus(DMA1_FLAG_TC1) == RESET)
        ;                         // 等待传输完成
    DMA_ClearFlag(DMA1_FLAG_TC1); // 清除传输完成标志
}